package com.qf.controller;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.serviceImpi.UserServiceImpl;
import com.qf.util.Constants;
import com.qf.util.StrUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

//用户登录
@WebServlet("/user")
public class UserController extends BaseServlet {
    //检查用户名是否可用
    public void check(HttpServletRequest request, HttpServletResponse response) {
        //接收参数
        String username = request.getParameter("username");
        // 调用service
        UserService service = new UserServiceImpl();
        boolean result = service.check(username);
        try {
            if (result) {
                response.getWriter().write(Constants.NOT_HAS_USER);
            } else {
                response.getWriter().write(Constants.HAS_USER);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    用户注册
    public String register(HttpServletRequest request, HttpServletResponse response) {
        //1. 获取页面传入的所有参数, key就是页面input框的name属性, value就是input框中输入的值
        Map<String, String[]> parameterMap = request.getParameterMap();

        //2. 将参数封装成User对象
        //创建用户对象
        User user = new User();
        //利用beanUtils工具类, 将map中的数据全部自动set到user对象中
        //使用要求: user对象的属性名必须和页面input框的name属性一致, 实体类必须实现Serializable序列化接口
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        UserService userService = new UserServiceImpl();
        int count = userService.createUser(user);

        if (count > 0){
            return "redirect:/registerSuccess.jsp";
        }else {
            return "redirect:/register.jsp";
        }
    }

    //    用户登录
    public String login(HttpServletRequest request, HttpServletResponse response) {
//      获取前端参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String auto = request.getParameter("auto");
//      空值判断，若为空，转发到登录页面
        if (!StrUtils.empty(username) || !StrUtils.empty(password) || !StrUtils.empty(code)) {
            request.setAttribute("msg", "用户名、密码、验证码不能为空！");
            return "forward:/login.jsp";
        }
//        验证码正误判断，若错，转发到登录页面
        String sessionCode = (String) request.getSession().getAttribute("code");
        if (!sessionCode.equalsIgnoreCase(code)) {
            request.setAttribute("msg", "验证码错误！");
            return "forward:/login.jsp";
        }

        UserService service = new UserServiceImpl();
        User user = service.login(username, password);

        if (user == null) {
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            request.setAttribute("msg", "用户名或密码错误！");
        }

        HttpSession session = request.getSession();
        session.setAttribute("loginUser", user);
//      判断是否自动登录，自动登录设置
        if ("on".equals(auto)) {
            Cookie cookie = new Cookie(Constants.AUTO_NAME, user.getUsername());
//            设置保存cookie的路径
            cookie.setPath("/");
//            设置保存时间
            cookie.setMaxAge(60 * 60 * 24 * 14);
//            通过响应将cookie数据写回到浏览器保存
            response.addCookie(cookie);
        }

        return "redirect:/index.jsp";
    }
}
